package com.prodavalnik.controller;


import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.prodavalnik.model.*;
/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	/**
	 * 
	 * @param username
	 * @param password
	 * @return User if username and password are correct , null otherwise
	 * @throws SQLException
	 */
	public User verifyingUserAndPass(String username,String password) throws SQLException{
		
		User user;
		if(DataBaseController.returnUserByUsernameAndPassword(username, password) != null){
			user = DataBaseController.returnUserByUsernameAndPassword(username, password);
			return user;
		}
		return null;
	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
	PrintWriter writer = response.getWriter();

	HttpSession session = request.getSession();
		
	Cookie cookie;

	String username = request.getParameter("name");
	String password = request.getParameter("password");
	String checked = request.getParameter("check");
	String isCookie = request.getParameter("existCookie");
	
	if(isCookie!=null && isCookie.equals("true")){
		session.setAttribute("username",username);
		session.setAttribute("password",password);
		writer.write("true");
		return;
	}
	
	if(isCookie == null && checked!=null && checked.equals("true")){
		cookie = new Cookie(username, password);
		cookie.setValue(username);
		cookie.setMaxAge(24 * 60 * 60);
		response.addCookie(cookie);
	}
	
	session.setAttribute("username",username);
	session.setAttribute("password",password);
	
	
	try {
		if (verifyingUserAndPass(username, password) == null){
			writer.print("error");
		}
		else{
				writer.print(username);
		}
			
	} catch (SQLException e) {
		e.printStackTrace();
	}

	}

}
